package com.gy.assistant.ui.conversationlist;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

import im.zego.zim.ZIM;
import im.zego.zim.callback.ZIMConversationDeletedCallback;
import im.zego.zim.callback.ZIMConversationListQueriedCallback;
import im.zego.zim.callback.ZIMConversationNotificationStatusSetCallback;
import im.zego.zim.callback.ZIMConversationPinnedStateUpdatedCallback;
import im.zego.zim.entity.ZIMConversation;
import im.zego.zim.entity.ZIMConversationChangeInfo;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMMessageDeletedInfo;
import im.zego.zim.enums.ZIMConversationEvent;
import im.zego.zim.enums.ZIMConversationNotificationStatus;
import im.zego.zim.enums.ZIMConversationType;
import im.zego.zim.enums.ZIMErrorCode;
import im.zego.zim.enums.ZIMMessageDeleteType;
import com.gy.assistant.R;
import com.gy.assistant.SDKManager;
import com.gy.assistant.ui.chat.group.ZIMGroupChatActivity;
import com.gy.assistant.ui.chat.peer.ZIMPeerChatActivity;
import com.gy.assistant.ui.chat.room.ZIMRoomChatActivity;

public class ZIMConversationFragment extends Fragment implements ZIMConversationListQueriedCallback {

    private static final String TAG = "ZIMConversationFragment";

    private static final int QUERY_CONVERSATION_COUNT = 20;
    private ConversationListAdapter conversationListAdapter = new ConversationListAdapter();
    private boolean isLoading = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_conversation_list, container, false);

        RecyclerView conversationRecyclerView = rootView.findViewById(R.id.conversation_list);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getContext(), LinearLayoutManager.VERTICAL, false);
        conversationRecyclerView.setLayoutManager(linearLayoutManager);
        conversationRecyclerView.setAdapter(conversationListAdapter);
        conversationRecyclerView.setItemAnimator(new DefaultItemAnimator());

        conversationRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == conversationListAdapter.getItemCount()) {
                    if (!isLoading) {
                        isLoading = true;
                        loadConversationList();
                    }
                }
            }
        });

        setHasOptionsMenu(true);
        setEventHandler();
        setItemClickEvent();

        return rootView;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loadConversationList();
    }

    private void setEventHandler() {
        SDKManager.sharedInstance().setConversationChangedCallback(new SDKManager.OnConversationChangedCallback() {
            @Override
            public void onConversationChanged(ZIM zim, ArrayList<ZIMConversationChangeInfo> conversationChangeInfoList) {
                for (ZIMConversationChangeInfo conversationChangeInfo : conversationChangeInfoList) {
                    if (conversationChangeInfo.event == ZIMConversationEvent.ADDED) {
                        conversationListAdapter.addOrUpdate(conversationChangeInfo.conversation);
                    } else if (conversationChangeInfo.event == ZIMConversationEvent.UPDATED) {
                        conversationListAdapter.addOrUpdate(conversationChangeInfo.conversation);
                    } else if (conversationChangeInfo.event == ZIMConversationEvent.DISABLED) {
                        conversationListAdapter.delete(conversationChangeInfo.conversation);
                    }
                }
                conversationListAdapter.sortAndNotify();
            }
        });
        SDKManager.sharedInstance().setMessageDeletedCallback(new SDKManager.OnMessageDeletedCallback() {
            @Override
            public void onMessageDeleted(ZIM zim, ZIMMessageDeletedInfo infos) {
                if (infos.messageDeleteType == ZIMMessageDeleteType.ALL_CONVERSATION_MESSAGES_DELETED){
                    SDKManager.sharedInstance().queryConversationList(null, QUERY_CONVERSATION_COUNT, new ZIMConversationListQueriedCallback() {
                        @Override
                        public void onConversationListQueried(ArrayList<ZIMConversation> conversationList, ZIMError errorInfo) {
                            handleConversationList(conversationList,errorInfo);
                        }
                    });
                }
            }
        });
    }

    private void setItemClickEvent() {
        conversationListAdapter.setOnItemClickListener(new ConversationListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, ZIMConversation conversation) {
                SDKManager.sharedInstance().clearConversationUnreadMessageCount(conversation.conversationID, conversation.type);
                if (conversation.type == ZIMConversationType.PEER) {
                    ZIMPeerChatActivity.actionStart(getActivity(), conversation.conversationID, conversation.conversationName,conversation.draft);
                } else if (conversation.type == ZIMConversationType.GROUP) {
                    ZIMGroupChatActivity.actionStart(getActivity(), conversation.conversationID, conversation.conversationName,conversation.draft);
                } else if (conversation.type == ZIMConversationType.ROOM) {
                    ZIMRoomChatActivity.actionStart(getActivity(), conversation.conversationID, conversation.conversationName,conversation.draft);
                }
            }
        });

        conversationListAdapter.setOnItemLongClickListener(new ConversationListAdapter.OnItemLongClickListener() {
            @Override
            public void onItemRemove(View view, ZIMConversation conversation) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                String[] item = new String[]{"删除", conversation.isPinned ? "取消置顶" : "置顶",conversation.notificationStatus == ZIMConversationNotificationStatus.NOTIFY?"免打扰":"取消免打扰"};
                builder.setSingleChoiceItems(item, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            //删除
                            SDKManager.sharedInstance().deleteConversation(conversation, new ZIMConversationDeletedCallback() {
                                @Override
                                public void onConversationDeleted(String conversationID, ZIMConversationType conversationType, ZIMError errorInfo) {
                                    conversationListAdapter.delete(conversation);
                                    conversationListAdapter.sortAndNotify();
                                    Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else if (which == 1) {
                            //置顶 or 取消置顶
                            SDKManager.sharedInstance().updateConversationPinned(item[which].equals("置顶"), conversation, new ZIMConversationPinnedStateUpdatedCallback() {
                                @Override
                                public void onConversationPinnedStateUpdated(String conversationID, ZIMConversationType conversationType, ZIMError errorInfo) {
                                }
                            });
                        }else if (which == 2){
                            ZIMConversationNotificationStatus notificationStatus = conversation.notificationStatus == ZIMConversationNotificationStatus.NOTIFY?ZIMConversationNotificationStatus.DO_NOT_DISTURB:ZIMConversationNotificationStatus.NOTIFY;
                            SDKManager.sharedInstance().setConversationNotificationStatus(notificationStatus, conversation.conversationID, conversation.type, new ZIMConversationNotificationStatusSetCallback() {
                                @Override
                                public void onConversationNotificationStatusSet(String conversationID, ZIMConversationType conversationType, ZIMError errorInfo) {
                                    if (errorInfo.code == ZIMErrorCode.SUCCESS){
                                        conversationListAdapter.updateNotificationStatus(conversationID,conversationType,notificationStatus);
                                    }
                                }
                            });
                        }
                        dialog.dismiss();
                    }
                });

                builder.create().show();
            }
        });
    }

    private void loadConversationList() {
        SDKManager.sharedInstance().queryConversationList(conversationListAdapter.getLastConversation(), QUERY_CONVERSATION_COUNT, this);
    }

    @Override
    public void onConversationListQueried(ArrayList<ZIMConversation> conversationList, ZIMError errorInfo) {
        handleConversationList(conversationList, errorInfo);
    }

    private void handleConversationList(ArrayList<ZIMConversation> conversationList, ZIMError errorInfo) {
        if (errorInfo.code != ZIMErrorCode.SUCCESS) {
            Toast.makeText(getActivity(), "Failed to query conversation, error:" + errorInfo.code, Toast.LENGTH_SHORT).show();
            return;
        }
        for (ZIMConversation conversation : conversationList) {
            conversationListAdapter.addOrUpdate(conversation);
        }
        conversationListAdapter.sortAndNotify();
        isLoading = false;
    }
}
